const express = require("express");
const router = express.Router();
const connection = require('../mysql')
var Response = require('../response');
const judgePhone = /^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/;
/**
 * 实现登录验证功能
 */
router.post('/', function (req, res, next) {

    let username = req.body.username;
    let password = req.body.password;
    let response = new Response(false, '', -1);
    if (username && password) {
        const st = new RegExp(judgePhone);
        let selectSQL = ""
        if (st.test(username)) {
            selectSQL = "SELECT * FROM user WHERE phone = ?"
        } else {
            selectSQL = "SELECT * FROM user WHERE username = ?"
        }
        connection.query(selectSQL, [username], function (error, results, fields) {
            console.log(results);
            if (results.length == 0) {
                response = new Response(false, '用户名或手机号错误', -1);
                res.send(response);
                return
            }
            if (results.length >= 1) {
                if (results[0].password == password && (results[0].username == username || results[0].phone == username)) {
                    //3、密码相同则登陆成功
                    response = new Response(true, '登陆成功', 200);
                    res.send(response);

                } else {
                    response = new Response(true, '登陆失败,密码错误', -1);
                    res.send(response);
                }
            }
        })
    } else {
        response = new Response(true, '登录失败,用户名和密码不能为空', -1);
        res.send(response);
    }
})
module.exports = router;